package com.yonyou.pmclouds.comprehensiveacceptance.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.yonyou.pmclouds.ApplicationConsts;
import com.yonyou.pmclouds.basecom.annotation.Insert;
import com.yonyou.pmclouds.basecom.entity.AdditionalPropertiesVOWrapper;
import com.yonyou.pmclouds.basecom.exception.BusinessException;
import com.yonyou.pmclouds.basecom.service.CommonPropertiesProcessor;
import com.yonyou.pmclouds.comprehensiveacceptance.entity.ComprehensiveAcceptanceVO;
import com.yonyou.pmclouds.comprehensiveacceptance.entity.AcceptStandardVOToNCC;
import com.yonyou.pmclouds.comprehensiveacceptance.rmiitf.ComprehensiveAcceptanceMaintain;
import com.yonyou.pmclouds.comprehensiveacceptance.rmiitf.ComprehensiveAcceptanceQuery;
import com.yonyou.pmclouds.enterprise.entity.EnterpriseInfo;
import com.yonyou.pmclouds.inspectitem.entity.InspectItemVO;
import com.yonyou.pmclouds.inspectitem.rmiitf.InspectItemService;
import com.yonyou.pmclouds.outter.enterprise.EnterpriseInfoQuery;
import com.yonyou.pmclouds.outter.user.UserInfoQuery;
import com.yonyou.pmclouds.workflow.aspect.PMApprove;
import com.yonyou.pmclouds.workquality.entity.WorkqualityCheckTypeEnum;
import com.yonyou.pmclouds.workquality.entity.WorkqualityVO;
import com.yonyou.pmclouds.workquality.service.rmiitf.WorkqualityQueryService;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

@RestController
@RequestMapping(value = {"/mobile/comprehensiveacceptance","/outter/comprehensiveacceptance"})
public class ComprehensiveAcceptanceController {
    @Reference(version = ApplicationConsts.APPLICATION_VERSION)
    private ComprehensiveAcceptanceMaintain acceptanceMaintain;

    @Reference(version = ApplicationConsts.APPLICATION_VERSION)
    private ComprehensiveAcceptanceQuery acceptanceQuery;

    @Reference(version = ApplicationConsts.APPLICATION_VERSION)
    private WorkqualityQueryService workqualityQueryService;

    @Reference(version = ApplicationConsts.APPLICATION_VERSION)
    private InspectItemService inspectItemService;
    @Autowired
    private UserInfoQuery userQuery;
    @Autowired
    private EnterpriseInfoQuery enterpriseInfoQuery;
    @Autowired
    private CommonPropertiesProcessor propertiesProcessor;

    private static final String[] USER_ID_FIELDS = {ComprehensiveAcceptanceVO.CREATOR};
    private static final String[] USER_NAME_FIELDS = {ComprehensiveAcceptanceVO.CREATOR_NAME};

    /**
     * 是否允许当前项目添加综合验收单，满足以下2点可以添加 :
     * 1.该项目不存在未解决的项目问题
     * 2.该项目没有已经通过的综合验收单
     *
     * @param pkProject
     * @return
     * @throws BusinessException
     */
    @GetMapping("/allowToAdd")
    public Map<Boolean, String> allowToAdd(String pkProject) throws BusinessException {
        return acceptanceQuery.allowToAdd(pkProject);
    }

    /**
     * 获取综合验收特有的检查标准列表（检查标准中，类型为综合验收的检查标准）
     *
     * @return
     * @throws BusinessException
     */
    @GetMapping("/getAcceptanceWorkQuality")
    public List<WorkqualityVO> getAcceptanceWorkQuality(String tenantId) throws BusinessException {
        return workqualityQueryService.queryByChecktypes(tenantId, WorkqualityCheckTypeEnum.COMPREHENSIVE_ACCEPTANCE.getValue());
    }

    /**
     * 保存填写的综合验收单信息
     *
     * @param acceptanceVO
     * @param errors
     * @return
     * @throws BusinessException
     */
    @Insert
    @PostMapping("/add")
    @PMApprove
    public ComprehensiveAcceptanceVO add(@RequestBody @Validated ComprehensiveAcceptanceVO acceptanceVO, BindingResult errors)
            throws BusinessException {
        if (errors.hasErrors()) {
            StringBuffer msg = new StringBuffer();
            for (int i = 0; i < errors.getAllErrors().size(); i++) {
                msg.append(errors.getAllErrors().get(i).getDefaultMessage());
                msg.append(",");
            }
            throw new BusinessException(msg.toString());
        }

        // 提交校验是否存在未关闭的问题
        Map<Boolean, String> checkResultMap = this.allowToAdd(acceptanceVO.getPkProject());
        if(checkResultMap != null && StringUtils.isNotEmpty(checkResultMap.get(Boolean.FALSE))){
            throw new BusinessException(checkResultMap.get(Boolean.FALSE));
        }

        ComprehensiveAcceptanceVO resultVO = acceptanceMaintain.insert(acceptanceVO);
        userQuery.tranUserInfoField(new ComprehensiveAcceptanceVO[]{resultVO}, USER_ID_FIELDS, USER_NAME_FIELDS);
        return acceptanceVO;
    }

    /**
     * 驳回修改综合验收单
     *
     * @param acceptanceVO
     * @param errors
     * @return
     * @throws BusinessException
     */
    @PostMapping("/update")
    @PMApprove(trigger = "commit")
    public ComprehensiveAcceptanceVO update(@RequestBody @Validated ComprehensiveAcceptanceVO acceptanceVO, BindingResult errors)
            throws BusinessException {
        if (errors.hasErrors()) {
            StringBuffer msg = new StringBuffer();
            for (int i = 0; i < errors.getAllErrors().size(); i++) {
                msg.append(errors.getAllErrors().get(i).getDefaultMessage());
                msg.append(",");
            }
            throw new BusinessException(msg.toString());
        }
        ComprehensiveAcceptanceVO resultVO = acceptanceMaintain.update(acceptanceVO);
        userQuery.tranUserInfoField(new ComprehensiveAcceptanceVO[]{resultVO}, USER_ID_FIELDS, USER_NAME_FIELDS);
        return acceptanceVO;
    }

    /**
     * 通过项目查询所有的综合验收单信息
     *
     * @param pkProject
     * @return
     * @throws BusinessException
     */
    @RequestMapping(value = "/queryByProject")
    public AdditionalPropertiesVOWrapper[] queryByProject(String pkProject)
            throws BusinessException {
        ComprehensiveAcceptanceVO[] vos = acceptanceQuery.queryByProject(pkProject);
        if (ArrayUtils.isEmpty(vos)) {
            return new AdditionalPropertiesVOWrapper[0];
        }
        Set<String> constructionUnitPks = new HashSet<>();
        // 取到所有施工单位的pk,获取施工单位信息
        for (ComprehensiveAcceptanceVO comprehensiveAcceptanceVO : vos) {
            constructionUnitPks.add(comprehensiveAcceptanceVO.getPkConstructionunit());
        }
        Map<String, EnterpriseInfo> enterpriseInfoMap = enterpriseInfoQuery
                .queryEnterpriseByIds(constructionUnitPks.toArray(new String[0]));
        for (ComprehensiveAcceptanceVO comprehensiveAcceptanceVO : vos) {
            EnterpriseInfo enterpriseInfo = enterpriseInfoMap.get(comprehensiveAcceptanceVO.getPkConstructionunit());
            comprehensiveAcceptanceVO.setConstructionName(enterpriseInfo == null ? "" : enterpriseInfo.getName());
        }
        userQuery.tranUserInfoField(vos, USER_ID_FIELDS, USER_NAME_FIELDS);
        return propertiesProcessor.wrapAdditionalProps(vos);
    }

    @RequestMapping("/getAcceptanceDetail")
    public ComprehensiveAcceptanceVO getAcceptanceDetail(String pkComprehensiveAcceptance) throws BusinessException {
        ComprehensiveAcceptanceVO acceptanceVO = acceptanceQuery.queryOneByPk(pkComprehensiveAcceptance);
        // 填充施工单位信息
        String pkConstructionunit = acceptanceVO.getPkConstructionunit();
        if (!StringUtils.isEmpty(pkConstructionunit)) {
            EnterpriseInfo enterpriseInfo = enterpriseInfoQuery.queryEnterpriseById(pkConstructionunit);
            acceptanceVO.setConstructionName(enterpriseInfo == null ? "" : enterpriseInfo.getName());
        }
        userQuery.tranUserInfoField(new ComprehensiveAcceptanceVO[]{acceptanceVO}, USER_ID_FIELDS, USER_NAME_FIELDS);
        return acceptanceVO;
    }

    /**
     * 查看验收项详细信息
     *
     * @param pkInspectitem
     * @return
     * @throws BusinessException
     */
    @RequestMapping(value = "/getInspectItemDetail")
    public InspectItemVO queryInspectItemVO(String pkInspectitem)
            throws BusinessException {
        return inspectItemService.queryOne(pkInspectitem);
    }

    @GetMapping("/checkCommit")
    public Object checkCommit(String pkProject) throws BusinessException {
        return acceptanceQuery.checkToCommit(pkProject);
    }

    @GetMapping("/getStandardByProject")
    public Object getInspectionStandardToNCC(@RequestParam("pkProject") String pkProject) throws BusinessException {
        return acceptanceQuery.getInspectionStandardToNCC(pkProject);
    }

}
